package cn.tedu.io;

import java.io.*;
import java.util.Scanner;

/**需求：通过流来完成文件的复制操作*/
public class TestCopyFile {
    public static void main(String[] args) {
        System.out.println("请输入源文件路径：");
        String f=new Scanner(System.in).nextLine();
        System.out.println("请输目标文件路径：");
        String t=new Scanner(System.in).nextLine();
//        ZFfileCopy(f,t);
        ZJfileCopy(f,t);
    }

    private static void ZFfileCopy(String f, String t) {
        Reader in=null;
        Writer out=null;
        try {
            in=new BufferedReader(new FileReader(f));
            out=new BufferedWriter(new FileWriter(t));
            int b;
            while ((b=in.read())!=-1){//循环读取源文件中的内容
                out.write(b);//将本轮中读到的内容写到复制文件中
                //out.flush();
            }
            System.out.println("恭喜您，复制成功！");
        } catch (Exception e) {
            System.out.println("很遗憾，复制失败");
            e.printStackTrace();
        }finally {
            /**一定会被执行到的代码需要放在finally{}中，比如关流操作
             * 关流是有顺序的：如果有多个流，最后创建的流最先关闭
             * 而且多条关流语句需要各自try-catch*/
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    private static void ZJfileCopy(String f, String t) {
        InputStream in=null;
        OutputStream out=null;
        try {
            in=new BufferedInputStream(new FileInputStream(f));
            out=new BufferedOutputStream(new FileOutputStream(t));
            int b;
            while ((b=in.read())!=-1){
                out.write(b);
            }
            System.out.println("恭喜您，复制成功！");
        } catch (Exception e) {
            System.out.println("很遗憾，复制失败！");
            e.printStackTrace();
        }finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
